//
//  YZPublishCommunityViewModel.m
//  VET
//
//  Created by YZ on 2018/7/10.
//  Copyright © 2018年 YZ. All rights reserved.
//

#import "YZPublishCommunityViewModel.h"
#import "YZMapManager.h"

typedef NS_ENUM(NSInteger,YZAttachMentType) {
    YZAttachMentTypeImage,
    YZAttachMentTypeVideo
};


@interface YZPublishCommunityViewModel()

@property (nonatomic, strong) YZMapManager *mapManager;

@property (nonatomic, assign, readwrite) BOOL success;

@property (nonatomic, copy)YZNetworkCompletionSuccessBlock successBlock;

@property (nonatomic, copy)YZNetworkCompletionFailBlock failBlock;

@property (nonatomic, strong) NSDictionary *attri;

@property (nonatomic, strong) NSDictionary *oreDic;

@end

@implementation YZPublishCommunityViewModel

@synthesize dataSource = _dataSource;

- (instancetype)init
{
    if(self = [super init]){
        _oreDic = @{@(1):@"top",@(2):@"bottom",@(3):@"right",@(4):@"left"};
        [self config];
    }
    return self;
}

- (void)config
{
    _selectedPhotos = @[];
    _selectedAssets = @[];
    
    YZPublishCommunityImgModel *imgModel = [YZPublishCommunityImgModel new];
    imgModel.addImg = [UIImage imageNamed:@"ico_im_more"];
    
    YZPublishCommunityContentModel *contentModel = [YZPublishCommunityContentModel new];
//    contentModel.contentText = @"";
    [contentModel.imgs addObject:imgModel];
    
    YZPublishCommunityFunctionModel *addressModel = [YZPublishCommunityFunctionModel new];
    addressModel.logo = @"ico_lbs";
    addressModel.title = @"所在位置";
    addressModel.selectTitle = @"请选择";
    addressModel.transferImg = @"ico_right";
    addressModel.normal = YES;
    addressModel.functionType = YZCommunityFunctionTypeLocation;
    
    YZPublishCommunityFunctionModel *visableModel = [YZPublishCommunityFunctionModel new];
    visableModel.logo = @"ico_whocansee";
    visableModel.title = @"谁可以看";
    visableModel.selectTitle = @"公开";
    visableModel.transferImg = @"ico_right";
    visableModel.normal = YES;
    visableModel.functionType = YZCommunityFunctionTypeVisable;
    
    _dataSource = @[@[contentModel],@[addressModel,visableModel]];
}

- (void)startRequestCommunityLocating
{
    [self.mapManager startLocating];
}

- (void)stopRequestCommunityLocating
{
    [self.mapManager stopLocating];
}

- (void)publishCommunitySuccess:(YZNetworkCompletionSuccessBlock)successBlock fail:(YZNetworkCompletionFailBlock)failBlock
{
    self.successBlock = successBlock;
    self.failBlock = failBlock;
    self.loading = YES;
    if ([((YZPublishCommunityContentModel *)[self modelsInSection:0].firstObject).imgs.firstObject isKindOfClass:[YZPublishCommunityVideoModel class]]) {//传视频
        
        CGFloat height = 0;
        CGFloat width = 0;
        if (self.videoOrientation == 1 || self.videoOrientation == 2) {
            height =  kScreenHeight;
            width = kScreenWidth;
        }else if(self.videoOrientation == 3 || self.videoOrientation == 4)
        {
            width = kScreenWidth;
            height = kScreenWidth*kScreenWidth/kScreenHeight;
        }
        self.attri = @{
                       @"mediaHeight":[NSString stringWithFormat:@"%@",@((NSInteger)height)],
                       @"mediaWidth":[NSString stringWithFormat:@"%@",@((NSInteger)width)],
                       @"mediaOrientation":self.oreDic[@(self.videoOrientation)]
                       };
        
        [YZNetworkManager uploadVideoWithApi:@"/api/file" params:nil videoUrl:((YZPublishCommunityVideoModel *)((YZPublishCommunityContentModel *)[self modelsInSection:0].firstObject).imgs.firstObject).url name:@"files" withHeaders:nil success:^(NSObject *obj) {
            NSLog(@"%@",obj);
            NSArray *urls = ((NSDictionary *)obj)[@"data"];
            NSString *attachmentType = @"1";
            [self publishCommunityWithAttachmentType:attachmentType andUrls:urls withAttachMentType:YZAttachMentTypeVideo];
        } fail:^(NSError *error) {
            self.loading = NO;
            if (failBlock) {
                failBlock(error);
            }
        }];
    }else
    {//传图片
        if(self.selectedPhotos.count == 1){
            UIImage *img = self.selectedPhotos.firstObject;
            self.attri = @{
                           @"mediaHeight":[NSString stringWithFormat:@"%@",@((NSInteger)img.size.height)],
                           @"mediaWidth":[NSString stringWithFormat:@"%@",@((NSInteger)img.size.width)]
                           
                           };
        }
        [YZNetworkManager uploadImgsWithApi:@"/api/file" params:nil imgs:self.selectedPhotos name:@"files" withHeaders:nil success:^(NSObject *obj) {
            NSLog(@"%@",obj);
            NSArray *urls = ((NSDictionary *)obj)[@"data"];
            NSString *attachmentType = @"0";
            [self publishCommunityWithAttachmentType:attachmentType andUrls:urls withAttachMentType:YZAttachMentTypeImage];
        } fail:^(NSError *error) {
            NSLog(@"%@",error);
            self.loading = NO;
            if (failBlock) {
                failBlock(error);
            }
        }];
    }
}

- (void)publishCommunityWithAttachmentType:(NSString *)attachmentType andUrls:(NSArray *)urls withAttachMentType:(YZAttachMentType)type
{
    NSString *content = ((YZPublishCommunityContentModel *)[self modelsInSection:0].firstObject).contentText;
    NSString *location = nil;
    if (((YZPublishCommunityFunctionModel *)[self modelInSection:1 row:0]).selectTitle.length == 0) {
        location = ((YZPublishCommunityFunctionModel *)[self modelInSection:1 row:0]).title;
    }
    NSString *whoWatch = [((YZPublishCommunityFunctionModel *)[self modelInSection:1 row:1]).selectTitle isEqualToString:@"公开"]?@"public":@"friends";
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithDictionary:@{
                                                                                  @"attachmentType":attachmentType,
                                                                                  @"content":content?content:@"",
                                                                                  @"location":location?location:@"",
                                                                                  @"whoWatch":whoWatch
                                                                                  }];
    
    if (urls.count == 1) {//单图，视频
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        [dic setObject:urls.firstObject forKey:@"url"];
        [dic addEntriesFromDictionary:self.attri];
        [params addEntriesFromDictionary:@{@"attachmentUrls":@[dic]}];
    }else
    {
        NSMutableArray *arr = [NSMutableArray array];
        for (NSString *url in urls) {
            [arr addObject:@{@"url":url}];
        }
        NSDictionary *urlDic = @{@"attachmentUrls":arr};
        [params addEntriesFromDictionary:urlDic];
    }
    
    [YZNetworkManager postWithApi:@"/api/activity" params:params withHeaders:nil success:^(NSObject *obj) {
        self.loading = NO;
        NSLog(@"%@",obj);
        if (self.successBlock) {
            self.successBlock(obj);
        }
    } fail:^(NSError *error) {
        NSLog(@"%@",error);
        self.loading = NO;
        if (self.failBlock) {
            self.failBlock(error);
        }
    }];
}

#pragma mark -- setters && getters

- (CLLocation *)getCommunityLocattion
{
    return [self.mapManager getCurrentLocation];
}

- (YZMapManager *)mapManager
{
    if (!_mapManager) {
        _mapManager = [[YZMapManager alloc] init];
    }
    return _mapManager;
}

- (void)setSelectedPhotos:(NSArray<UIImage *> *)selectedPhotos
{
    _selectedPhotos = selectedPhotos;
    YZPublishCommunityContentModel *contentModel = (YZPublishCommunityContentModel *)[self modelInSection:0 row:0];
    NSMutableArray *arr = [NSMutableArray array];
    for (UIImage *img in selectedPhotos) {
        YZPublishCommunityImgModel *model = [YZPublishCommunityImgModel new];
        model.img = img;
        [arr addObject:model];
    }
    if (arr.count != 9) {//如果没有9 则显示添加
        [arr addObject:contentModel.imgs.lastObject];
    }
    contentModel.imgs = arr;
}

- (void)setCurrentVideoAssertInfo:(NSDictionary *)currentVideoAssertInfo
{
    _currentVideoAssertInfo = currentVideoAssertInfo;
    PHAsset *currentVideoAssert = currentVideoAssertInfo[@"assert"];
    NSURL *url = currentVideoAssertInfo[@"url"];
    YZPublishCommunityContentModel *contentModel = (YZPublishCommunityContentModel *)[self modelInSection:0 row:0];
    if (currentVideoAssert) {
        YZPublishCommunityVideoModel *model = [YZPublishCommunityVideoModel new];
        model.assert = currentVideoAssert;
        model.url = url;
        contentModel.imgs = @[model];
    }else
    {
        YZPublishCommunityImgModel *imgModel = [YZPublishCommunityImgModel new];
        imgModel.addImg = [UIImage imageNamed:@"ico_im_more"];
        contentModel.imgs = @[imgModel];
    }
}
@end
